<script setup lang="ts">
import { onMounted, ref, onUnmounted, watch, reactive } from 'vue';
import * as echarts from 'echarts'
import type { RentAdvent, WorkbenchDataType } from '@/types/workbench';
import { getRentInfoAPI, getWorkbenchAPI } from '@/apis/workbench';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { outRentAPI } from '@/apis/enterprise';
import { useUserDetailStore } from '@/stores/userDetail';

const router = useRouter()
// 获取用户权限列表
const userDetailStore = useUserDetailStore()
const userPermission = userDetailStore.userDetail.permissions

// 基础数据 - 图表数据
const workBenchData = ref<WorkbenchDataType>({} as WorkbenchDataType)
const getWorkBench = async () => {
  const res = await getWorkbenchAPI()
  workBenchData.value = res.data
}
getWorkBench()

// 图表
const chartRef = ref<HTMLDivElement | null>(null)
let myChart: echarts.ECharts | null = null

// 图表初始化函数
const initChart = () => {
  if (chartRef.value) {
    if (!myChart) {
      myChart = echarts.init(chartRef.value);
    }

    const option: echarts.EChartsOption = {
      title: {
        text: '年度收入统计'
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['物业费', '行车收入']
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: workBenchData.value.annualIncomeArray?.xmonth || [],
      },
      yAxis: {
        type: 'value',
      },
      series: [
        {
          name: '物业费',
          type: 'bar',
          stack: 'total',
          barWidth: 20,
          emphasis: {
            focus: 'series'
          },
          data: workBenchData.value.annualIncomeArray?.ybuilding || [],
          itemStyle: {
            color: '#4B7BE9'
          }
        },
        {
          name: '行车收入',
          type: 'bar',
          stack: 'total',
          barWidth: 20,
          emphasis: {
            focus: 'series'
          },
          data: workBenchData.value.annualIncomeArray?.yparking || [],
          itemStyle: {
            color: '#B5CCFF'
          }
        }
      ]
    };

    myChart.setOption(option);
  }
};

// 监听基础数据变化
watch(
  () => workBenchData.value.annualIncomeArray,
  () => {
    initChart();
  },
  { deep: true }
);

onMounted(() => {
  initChart();
})

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
})

// 临期合同 ----------------
const rentInfoParams = reactive<{
  page: number,
  pageSize: number
}>({
  page: 1,
  pageSize: 5
})
const rentInfo = ref<RentAdvent[]>([])
const total = ref(0)
const getRentInfo = async () => {
  const res = await getRentInfoAPI(rentInfoParams)
  rentInfo.value = res.data.rows
  total.value = res.data.total
}

if (userPermission.includes('park:enterprise:list') || userPermission.includes('*:*:*')) {
  getRentInfo()
}

// 续费合同 ----------------
const goRenk = (id: number, scopeId: number) => {
  router.push({
    name: 'enterprise',
    query: {
      id,
      scopeId
    }
  })
}

// 退租
const backRent = async (id: string) => {
  await ElMessageBox.confirm('退租不可撤回，是否确认退租当前楼宇?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
  await outRentAPI(id)
  ElMessage.success('退租成功')
  getRentInfo()
}

</script>

<template>
  <div class="workbench-page">
    <el-row :gutter="20">
      <el-col :span="17">
        <!-- 基础数据 -->
        <div class="card-container">
          <div class="card-title">园区数据</div>
          <div class="card-statistic">
            <el-statistic :value="workBenchData.annualIncome">
              <template #title>年度累计收费（元）</template>
            </el-statistic>
            <el-statistic :value="workBenchData.enterpriseTotal">
              <template #title>入驻企业总数（个）</template>
            </el-statistic>
            <el-statistic :value="workBenchData.monthCardTotal">
              <template #title>月卡车辆总数（辆）</template>
            </el-statistic>
            <el-statistic :value="workBenchData.chargePoleTotal">
              <template #title>一体杆总数（台）</template>
            </el-statistic>
          </div>
        </div>
        <!-- 图表 -->
        <div class="card-container">
          <div class="card-title">
            <div class="echarts" ref="chartRef">
            </div>
          </div>
        </div>
        <!-- 表格 -->
        <div class="card-container">
          <div class="card-title">临期合同提醒</div>
          <!-- 临期合同表格 -->
          <div v-if="userPermission.includes('park:enterprise:list') || userPermission.includes('*:*:*')">
            <el-table :data="rentInfo">
              <el-table-column label="序号" type="index" width="100"></el-table-column>
              <el-table-column label="企业名称" prop="enterpriseName"></el-table-column>
              <el-table-column label="租赁楼宇" prop="buildingName"></el-table-column>
              <el-table-column label="租赁时间" width="200">
                <template #default="scope">
                  {{ scope.row.startTime }} - {{ scope.row.endTime }}
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template #default="{ row }">
                  <el-button type="primary" link @click="goRenk(row.id, row.enterpriseId)" v-permission="'park:rent:add_surrender'">续费</el-button>
                  <el-button type="primary" link @click="backRent(row.id)" v-permission="'park:rent:add_surrender'">退租</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页器 -->
            <div class="page-container" style="float: none !important; height: 60px;">
              <el-pagination 
                layout="total, sizes, prev, pager, next"
                :page-sizes="[2,5,10,20]"
                :total="total" 
                v-model:current-page="rentInfoParams.page" 
                v-model:page-size="rentInfoParams.pageSize"
                @change="getRentInfo()"
              />
            </div>
          </div>
          <!-- 无权限展示 -->
          <div class="no-permission" style="padding-top: 30px;" v-else>
            <img src="/src/assets/caixukun.svg" alt="403" class="error-img" style="height: 200px;">
            <h2 class="error-title">抱歉，您无权访问该功能</h2>
            <p class="error-desc">请联系管理员开通相关权限</p>
          </div>
        </div>
      </el-col>
      <el-col :span="7">
        <!-- 快捷导航 -->
        <div class="card-container">
          <div class="card-title">快捷入口</div>
          <div class="card-entry">
            <div class="card-entry-item" @click="$router.push('/exterpriseAdd')" v-permission="'park:enterprise:add_edit'">
              <img src="@/assets/entry-enterprise.png" alt="" />
              <span>添加企业</span>
            </div>
            <div class="card-entry-item" @click="$router.push('/sys/user')" v-permission="'sys:user:list'">
              <img src="@/assets/entry-employee.png" alt="" />
              <span>员工管理</span>
            </div>
            <div class="card-entry-item" @click="$router.push('/propety/cost?type=add')" v-permission="'park:propertyFee:add'">
              <img src="@/assets/entry-bill.png" alt="" />
              <span>添加账单</span>
            </div>
            <div class="card-entry-item">
              <img src="@/assets/entry-screen.png" />
              <span>数据大屏</span>
            </div>
          </div>
        </div>
        <!-- 该用户告警列表 -->
        <div class="card-container">
          <div class="card-title">设备告警派单</div>
          <!-- 哥哥 -->
          <div class="icon" style="width: 100%; display: flex; justify-content: center;">
            <img src="@/assets/caixukun-active.svg" alt="">
          </div>
          <!-- go警告 -->
          <div class="jing-gao" style="width: 100%; display: flex; justify-content: center; margin-top: 20px;">
            <el-button type="primary" @click="$router.push('/pole/waring')" v-permission="'pole:warning:list'" style="width: 100%;">更多 ></el-button>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<style lang="scss" scoped>
.no-permission {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #f5f7fa;

  .error-img {
    width: 300px;
    margin-bottom: 24px;
  }

  .error-title {
    font-size: 24px;
    color: #303133;
    margin-bottom: 16px;
  }

  .error-desc {
    font-size: 14px;
    color: #909399;
    margin-bottom: 24px;
  }
}
.echarts {
  width: 100%;
  height: 300px;
}

.workbench-page {
  background-color: #f4f6f8;
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
  overflow-x: hidden;
  .card-container {
    background-color: #fff;
    padding: 20px;
    margin-bottom: 20px;
  }
  .card-title {
    margin-bottom: 20px;
    font-size: 14px;
    font-weight: 500;
  }
  .card-statistic {
    display: flex;
    justify-content: space-between;
  }
}

.el-statistic {
  --el-statistic-content-font-size: 28px;
  --el-statistic-title-font-size: 13px;
}
:deep(.el-statistic__head) {
  margin-bottom: 12px;
}

.card-entry {
  display: flex;
  justify-content: space-between;
  &-item {
    text-align: center;
    img {
      width: 40px;
    }
    span {
      font-size: 12px;
      display: block;
      margin-top: 8px;
    }
  }
  .card-entry-item {
    cursor: pointer
  }
}
</style>
